package com.ruoyi.quarte;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ruoyi.business.domain.ShopCardnum;
import com.ruoyi.business.service.impl.ShopCardnumServiceImpl;
import com.ruoyi.business.service.impl.ShopOrderServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.concurrent.TimeUnit;

@Component
@Slf4j
public class MyScheduledTask {

    @Autowired
    private ShopOrderServiceImpl orderService;
    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private ShopCardnumServiceImpl cardnumService;


    // 在固定的时间点执行，更新订单信息,恢复库存,删除过期定案
    @Scheduled(cron = "0 0 2 * * ?")
    //@Scheduled(fixedDelay = 120000)//两分钟执行一次测试使用
    @Transactional(rollbackFor = Exception.class)
    public void task2() {
        //获取当前日期看是否是月初
        String time = DateUtil.format(new Date(), "yyyy-MM");
        ShopCardnum shopCardnum = cardnumService.getOne(new QueryWrapper<ShopCardnum>().lambda().eq(ShopCardnum::getMonth, time));
        log.info("--------------------------定时任务打印当前卡数量------------------------------------------");
        log.info("--------------------------" + JSON.toJSONString(shopCardnum) + "------------------------------------------");
        //获取本月已经发放卡卷的数量
        //查询已经发放的立减金数量
        int num = orderService.getCountMonth(time);
        shopCardnum.setNum(shopCardnum.getSumNum() - num);
        cardnumService.updateById(shopCardnum);
        //删除 获取昨天的日期 无用订单
        //更新redis数据
        // 当前时间
        long now = System.currentTimeMillis();
        // 本月月底时间
        long endOfMonth = DateUtil.endOfMonth(DateUtil.date()).getTime();
        // 计算相差秒数
        long seconds = (endOfMonth - now) / 1000;
        redisTemplate.opsForValue().set("order_num", shopCardnum.getNum(), seconds, TimeUnit.SECONDS);
        log.info("--------------------------" + shopCardnum.getNum() + "------------------------------------------");

    }


}
